package com.sharelogindemo;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mob.tools.utils.UIHandler;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

import static android.R.attr.action;

public class LoginActivity extends BaseActivity implements PlatformActionListener,Handler.Callback{
    private static final int MSG_ACTION_CCALLBACK = 0;
    private ImageView mImageWxLogin;
    private ImageView mImageQqLogin;
    private ProgressDialog mProgressDialog;
    private TextView control_text;
    private TextView mTextForgetPassword;
    private TextView mTextTitle;
    private ImageView mImagePasswordStatus;
    private boolean isHiddenPassword = true;
    private EditText account,password;
    private Button mButtonLogin,ButtonShare;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        initListener();
    }

    protected void initView() {
        mImageWxLogin = (ImageView) findViewById(R.id.iv_wx_login);
        mImageQqLogin = (ImageView) findViewById(R.id.iv_qq_login);
        back_layout = (LinearLayout) findViewById(R.id.back_layout);
        control_text = (TextView) findViewById(R.id.control_text);

        control_text.setText(R.string.register);
        control_text.setTextColor(getResources().getColor(R.color.title));
        mTextForgetPassword = (TextView) findViewById(R.id.forget_password);
        mImagePasswordStatus = (ImageView) findViewById(R.id.account_password_status);
        mButtonLogin = (Button) findViewById(R.id.login);
        ButtonShare = (Button) findViewById(R.id.share);
        mTextTitle = (TextView) findViewById(R.id.title);
        account = (EditText) findViewById(R.id.account);
        password = (EditText) findViewById(R.id.password);
        mTextTitle.setText(R.string.login);

        mButtonLogin.setClickable(false);
        account.addTextChangedListener(new AddTextChangeListener());
        password.addTextChangedListener(new AddTextChangeListener());
        control_text.setOnClickListener(this);
        mTextForgetPassword.setOnClickListener(this);
        mButtonLogin.setOnClickListener(this);
        ButtonShare.setOnClickListener(this);
        back_layout.setOnClickListener(this);
        mImagePasswordStatus.setOnClickListener(this);

    }

    protected void initListener() {
        mImageWxLogin.setOnClickListener(this);
        mImageQqLogin.setOnClickListener(this);
    }

    private class AddTextChangeListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String mAccount = account.getText().toString();
            String mPassword = password.getText().toString();
            if(Utils.isPhoneNumberValid(mAccount, Utils.COUNTRY_CHINA_CODE, true) && Utils.isPasswordNumber(mPassword)) {
                mButtonLogin.setBackgroundResource(R.drawable.account_login_bg);
                mButtonLogin.setClickable(true);
            }else {
                mButtonLogin.setBackgroundResource(R.drawable.account_no_login_bg);
                mButtonLogin.setClickable(false);
            }
            if(password.isFocused()) {
                if(!Utils.isPasswordNumber1(mPassword, password)) {
                    ToastUtil.showToast(LoginActivity.this, R.string.is_password);
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_wx_login:
                if(!Utils.isAppInstalled(LoginActivity.this,"com.tencent.mm")){
                    Toast.makeText(LoginActivity.this, "微信尚未安装", Toast.LENGTH_SHORT).show();
                }else {
                    Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                    wechat.setPlatformActionListener(this);
                    wechat.SSOSetting(false); //设置false表示使用SSO授权方式
                    authorize(wechat, 1);
                }
                break;
            case R.id.iv_qq_login:
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                qq.setPlatformActionListener(this);
                qq.SSOSetting(false);
                authorize(qq, 2);
                break;
            case R.id.account_password_status:
                if(isHiddenPassword) {
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mImagePasswordStatus.setBackgroundResource(R.mipmap.account_btn_show_nor);
                }else {
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mImagePasswordStatus.setBackgroundResource(R.mipmap.account_btn_show_sel);
                }
                isHiddenPassword = !isHiddenPassword;
                password.postInvalidate();
                //切换后将EditText光标置于末尾
                CharSequence charSequence = password.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }
                break;
            case R.id.login:
                break;
            case R.id.forget_password:
                Utils.startActivity(this,ForgetPasswordActivity.class);
                break;
            case R.id.control_text:
                Utils.startActivity(LoginActivity.this, RegisterActivity.class);
                break;
            case R.id.back_layout:
                finish();
                break;
            case R.id.share:
                Utils.startActivity(LoginActivity.this, ShareActivity.class);
                break;
        }
    }

    //授权
    private void authorize(Platform plat, int type) {
        switch (type) {
            case 1:
                showProgressDialog(getString(R.string.opening_wechat));
                break;
            case 2:
                showProgressDialog(getString(R.string.opening_qq));
                break;
        }
        if (plat.isAuthValid()) { //如果授权就删除授权资料
            plat.removeAccount(true);
        }
        plat.showUser(null);//授权并获取用户信息
    }

    //登陆授权成功的回调
    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> res) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 1;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);   //发送消息
        //遍历Map
        Iterator ite =res.entrySet().iterator();
        while (ite.hasNext()) {
            Map.Entry entry = (Map.Entry)ite.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            Log.i("登录用户信息",key+"： "+value);
        }

    }

    //登陆授权错误的回调
    @Override
    public void onError(Platform platform, int i, Throwable t) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 2;
        msg.arg2 = action;
        msg.obj = t;
        Log.i("登录",t.toString());
        UIHandler.sendMessage(msg, this);
    }

    //登陆授权取消的回调
    @Override
    public void onCancel(Platform platform, int i) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 3;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);
    }

    //登陆发送的handle消息在这里处理
    @Override
    public boolean handleMessage(Message message) {
        hideProgressDialog();
        switch (message.arg1) {
            case 1: { // 成功
                Toast.makeText(LoginActivity.this, "授权登陆成功", Toast.LENGTH_SHORT).show();
                //获取用户资料
                Platform platform = (Platform) message.obj;
                String userId = platform.getDb().getUserId();//获取用户账号
                String userName = platform.getDb().getUserName();//获取用户名字
                String userIcon = platform.getDb().getUserIcon();//获取用户头像
                String userGender = platform.getDb().getUserGender(); //获取用户性别，m = 男, f = 女，如果微信没有设置性别,默认返回null
                Toast.makeText(LoginActivity.this, "用户信息为--用户名：" + userName + "  性别：" + userGender, Toast.LENGTH_SHORT).show();
                Log.i("登录成功","用户信息为--用户名：" +userName+" 性别：" +userGender+"账号:"+userId+"用户头像:"+userIcon);
                //下面就可以利用获取的用户信息登录自己的服务器或者做自己想做的事啦!

            }
            break;
            case 2: { // 失败
                Toast.makeText(LoginActivity.this, "授权登陆失败", Toast.LENGTH_SHORT).show();
            }
            break;
            case 3: { // 取消
                Toast.makeText(LoginActivity.this, "授权登陆取消", Toast.LENGTH_SHORT).show();
            }
            break;
        }
        return false;
    }

    //显示dialog
    public void showProgressDialog(String message) {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage(message);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
    }

    //隐藏dialog
    public void hideProgressDialog() {
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
    }
}
